package org.zyx.user.service.impl;


import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.zyx.user.mapper.UserMapper;
import org.zyx.user.pojo.User;
import org.zyx.user.service.UserService;
import org.zyx.user.utils.CodecUtils;
import org.zyx.yiyou.common.utils.NumberUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 98050
 * @Time: 2018-10-21 18:42
 * @Feature:
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private AmqpTemplate amqpTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    static final Logger logger = LoggerFactory.getLogger(UserService.class);

    private static final String KEY_PREFIX = "user.verify";

    @Override
    public Boolean checkData(String data, Integer type) {
        User user = new User();
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                return null;
        }
        return this.userMapper.selectCount(user) == 0;//不存在则返回true
    }

    /**
     * 给手机发送验证码
     *
     * @param phone
     * @return
     */
    @Override
    public Boolean sendVerifyCode(String phone) {
        if (StringUtils.isBlank(phone)) {
            return false;
        }
        //1.生成验证码
        String code = NumberUtils.generateCode(6);
        //2.发送消息到RabbitMQ
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend("yiyou.sms.exchange", "sms.verify.code", msg);
        //3.把验证码保存到redis中,设置过期时间
        stringRedisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
        return true;
    }

    /**
     * 注册账号
     *
     * @param user
     * @param code
     */
    @Override
    public Boolean register(User user, String code) {
        String key = KEY_PREFIX + user.getPhone();
        //1.从redis中取出验证码
        String codeCache = this.stringRedisTemplate.opsForValue().get(key);
        //2.检查验证码是否正确
        if(!codeCache.equals(code)){
            //不正确，返回
            return false;
        }
        user.setId(null);
        user.setCreated(new Date());
        //3.密码加密
        String encodePassword = CodecUtils.passwordBcryptEncode(user.getUsername().trim(),user.getPassword().trim());
        user.setPassword(encodePassword);
        user.setSalt("Spring Security");
        //4.写入数据库
        boolean result = this.userMapper.insertSelective(user) == 1;
        //5.如果注册成功，则删掉redis中的code
        if (result){
            try{
                this.stringRedisTemplate.delete(KEY_PREFIX + user.getPhone());
            }catch (Exception e){
                logger.error("删除缓存验证码失败，code:{}",code,e);
            }
        }
        return result;
    }
    /**
     * 用户验证
     * @param username
     * @param password
     * @return
     */
    @Override
    public User queryUser(String username, String password) {
        //1.查询
        User record = new User();
        record.setUsername(username);
        User user = this.userMapper.selectOne(record);

        //2.校验用户名
        if (user == null){
            return null;
        }
        //3. 校验密码
        boolean result = CodecUtils.passwordConfirm(username + password,user.getPassword());
        if (!result){
            return null;
        }

        //4.用户名密码都正确
        return user;
    }


}
